import 'package:flutter_admin/api/odoo/sale_inquiry_form_odoo_api.dart';
import 'package:flutter_admin/api/odoo/sale_inquiry_product_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/sale_inquiry_form.dart';
import 'package:flutter_admin/models/odoo/sale_inquiry_product.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input_num.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/utils/eventbus.dart';

class SaleInquiryBrowseList extends StatefulWidget {
  SaleInquiryForm? saleInquiryForm;
  SaleInquiryBrowseList({required this.saleInquiryForm, Key? key})
      : super(key: key);

  @override
  _SaleInquiryBrowseList createState() => _SaleInquiryBrowseList();
}

class _SaleInquiryBrowseList extends State<SaleInquiryBrowseList> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  late SaleInquiryForm saleInquiryForm;
  SaleInquiryProduct saleInquiryProduct = SaleInquiryProduct();
  List tableList = [];
  @override
  void initState() {
    super.initState();
    this.saleInquiryForm = widget.saleInquiryForm ?? SaleInquiryForm();

    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadData();
    });
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 300,
            label: '报价单位',
            enable: false,
            value: saleInquiryForm.companyName,
          ),
          CryInput(
            width: 300,
            label: '事业部',
            enable: false,
            value: saleInquiryForm.deptName,
          ),
          CryInput(
            width: 300,
            label: '询价单编号',
            enable: false,
            value: saleInquiryForm.inquiryNo,
          ),
          CryInput(
            width: 300,
            label: '业务员',
            enable: false,
            value: saleInquiryForm.userName,
          ),
          CryInput(
            width: 300,
            label: '询价单位',
            enable: false,
            value: saleInquiryForm.partnerName,
          ),
          CryInput(
            width: 300,
            label: '电话',
            enable: false,
            value: saleInquiryForm.phone,
          ),
          CryInput(
            width: 300,
            label: '客户性质',
            enable: false,
            value: saleInquiryForm.customerNature,
          ),
          CryInput(
            width: 300,
            label: '邮箱',
            enable: false,
            value: saleInquiryForm.email,
          ),
          CryInput(
            width: 300,
            label: '付费方式',
            enable: false,
            value: saleInquiryForm.paymentMethod,
          ),
          CryInput(
            width: 300,
            label: '项目名称',
            enable: false,
            value: saleInquiryForm.projectName,
          ),
          CryInput(
            width: 300,
            label: '是否有目标价',
            enable: false,
            value: saleInquiryForm.isTargetprice == '1' ? '是' : '否',
          ),
          CryInput(
            width: 300,
            label: '到货地点',
            enable: false,
            value: saleInquiryForm.arrivalPlace,
          ),
          // 新增字段开始；
          CryInput(
            width: 300,
            label: '报价币种',
            enable: false,
            value: saleInquiryForm.currency,
            onSaved: (v) {
              saleInquiryForm.currency = v;
            },
          ),
          CryInputNum(
            width: 300,
            label: '下单汇率',
            enable: false,
            value: saleInquiryForm.exchangeRate,
            onSaved: (v) {
              saleInquiryForm.exchangeRate = v;
            },
          ),
          CryInputNum(
            width: 300,
            label: '税率',
            enable: false,
            value: saleInquiryForm.taxRate,
            onSaved: (v) {
              saleInquiryForm.taxRate = v;
            },
          ),
          CryInputNum(
            width: 300,
            label: '利润率',
            enable: false,
            value: saleInquiryForm.profitMargin,
            onSaved: (v) {
              saleInquiryForm.profitMargin = v;
            },
          ),
          CryInputNum(
            width: 300,
            label: '运输费用（元）',
            enable: false,
            value: saleInquiryForm.trafficExpense,
            onSaved: (v) {
              saleInquiryForm.trafficExpense = v;
            },
          ),
          CryInputNum(
            width: 300,
            label: '海运费/空运费（元）',
            enable: false,
            value: saleInquiryForm.oceanFreight,
            onSaved: (v) {
              saleInquiryForm.oceanFreight = v;
            },
          ),
          CryInputNum(
            width: 300,
            label: '运输保险（元）',
            enable: false,
            value: saleInquiryForm.transportationInsurance,
            onSaved: (v) {
              saleInquiryForm.transportationInsurance = v;
            },
          ),
          CryInputNum(
            width: 300,
            label: '保函费用（元）',
            enable: false,
            value: saleInquiryForm.guaranteeFee,
            onSaved: (v) {
              saleInquiryForm.guaranteeFee = v;
            },
          ),
          CryInputNum(
            width: 300,
            label: '熏蒸/热处理费（元）',
            enable: false,
            value: saleInquiryForm.heatTreatment,
            onSaved: (v) {
              saleInquiryForm.heatTreatment = v;
            },
          ),
          CryInputNum(
            width: 300,
            label: '报检代理费（元）',
            enable: false,
            value: saleInquiryForm.brokerageFee,
            onSaved: (v) {
              saleInquiryForm.brokerageFee = v;
            },
          ),
          CryInputNum(
            width: 300,
            label: '普惠制产地证（元）',
            enable: false,
            value: saleInquiryForm.COOFG,
            onSaved: (v) {
              saleInquiryForm.COOFG = v;
            },

          ),
          CryInputNum(
            width: 300,
            label: '试验费（元）',
            enable: false,
            value: saleInquiryForm.experimentalExpenses,
            onSaved: (v) {
              saleInquiryForm.experimentalExpenses = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '认证、公证费（元）',
            enable: false,
            value: saleInquiryForm.notarialFees,
            onSaved: (v) {
              saleInquiryForm.notarialFees = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '佣金（元）',
            enable: false,
            value: saleInquiryForm.commission,
            onSaved: (v) {
              saleInquiryForm.commission = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '厂验（元）',
            enable: false,
            value: saleInquiryForm.factoryInspection,
            onSaved: (v) {
              saleInquiryForm.factoryInspection = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '融资费用（元）',
            enable: false,
            value: saleInquiryForm.financing,
            onSaved: (v) {
              saleInquiryForm.financing = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '信用保险（元）',
            enable: false,
            value: saleInquiryForm.creditInsurance,
            onSaved: (v) {
              saleInquiryForm.creditInsurance = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '施工服务费（元）',
            enable: false,
            value: saleInquiryForm.constructionServiceFee,
            onSaved: (v) {
              saleInquiryForm.constructionServiceFee = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '其他费（元）',
            enable: false,
            value: saleInquiryForm.other,
            onSaved: (v) {
              saleInquiryForm.other = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '资信调查报告费（元）',
            enable: false,
            value: saleInquiryForm.surveyReport,
            onSaved: (v) {
              saleInquiryForm.surveyReport = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '费用合计（元）',
            enable: false,
            value: saleInquiryForm.amountTotal,
            onSaved: (v) {
              saleInquiryForm.amountTotal = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          CryInputNum(
            width: 300,
            label: '毛利润（元）',
            enable: false,
            value: saleInquiryForm.grossProfit,
            onSaved: (v) {
              saleInquiryForm.grossProfit = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
          // 新增字段结束；
          CryInput(
            label: '备注',
            enable: false,
            value: saleInquiryForm.comment,
          ),
        ],
      ),
    );
    var table = DataTable(
      columns: [
        DataColumn(label: Text('产品编码(图号)')),
        DataColumn(label: Text("产品名称")),
        DataColumn(label: Text("规格型号")),
        DataColumn(label: Text("技术要求")),
        DataColumn(label: Text("备注")),
        DataColumn(label: Text("数量")),
        DataColumn(label: Text("单价(元)")),
        DataColumn(label: Text("小计(元)")),
        DataColumn(label: Text('退税率')),
        DataColumn(label: Text('销售单价（外币）')),
        DataColumn(label: Text('核算含税价格（元）')),
        DataColumn(label: Text('核算不含税价格（元）')),
        DataColumn(label: Text('单位补税及税金附加（元）')),
        DataColumn(label: Text('单项利润率%')),
        DataColumn(label: Text('单项换汇成本')),
      ],
      rows: this.tableList.map((m) {
        SaleInquiryProduct saleInquiryProduct = SaleInquiryProduct.fromMap(m);

        var result = DataRow(cells: [
          DataCell(Text(saleInquiryProduct.productCode ?? '--')),
          DataCell(Text(saleInquiryProduct.productName ?? '--')),
          DataCell(Text(saleInquiryProduct.description ?? '--')),
          DataCell(Text(saleInquiryProduct.technicalRequirement ?? '--')),
          DataCell(Text(saleInquiryProduct.comment ?? '--')),
          DataCell(Text(saleInquiryProduct.quantity != null
              ? saleInquiryProduct.quantity.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.unitPrice != null
              ? saleInquiryProduct.unitPrice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.sum ?? '--')),
          DataCell(Text(saleInquiryProduct.taxrate != null
              ? saleInquiryProduct.taxrate.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.foreignprice != null
              ? saleInquiryProduct.foreignprice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.taxinclusiveprice != null
              ? saleInquiryProduct.taxinclusiveprice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.notaxinclusiveprice != null
              ? saleInquiryProduct.notaxinclusiveprice.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.taxsurcharges != null
              ? saleInquiryProduct.taxsurcharges.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.singleprofitmargin != null
              ? saleInquiryProduct.singleprofitmargin.toString()
              : '--')),
          DataCell(Text(saleInquiryProduct.summarycost != null
              ? saleInquiryProduct.summarycost.toString()
              : '--')),
        ]);
        return result;
      }).toList(),
    );
    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: '确认',
          onPressed: () {
            if (tableList.length > 0) {
              this.saleInquiryForm.state = '1';
              FormState form = formKey.currentState!;
              form.save();
              SaleInquiryFormOdooApi.saveOrUpdate(saleInquiryForm.toOdooMap())
                  .then((ResponseBodyApi res) {
                if (!res.success!) {
                  //CryUtils.message(re s.message!);
                  return;
                }
                Navigator.pop(context, true);
                CryUtils.message(S.of(context).saved);
                EventBus.getPublisher().add({"type": "form:saved"});
              });
            } else {
              CryUtils.message('产品明细为空不能生成报价单');
            }
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            final ModalRoute<Object?>? parentRoute = ModalRoute.of(context);
            final bool canPop = parentRoute?.canPop ?? false;

            if (canPop) {
              return BackButton();
            } else {
              return SizedBox.shrink();
            }
          },
        ),
        title: Text('产品明细'),
      ),
      body: SingleChildScrollView(
          child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          form,
          SingleChildScrollView(scrollDirection: Axis.horizontal, child: table),
        ],
      )),

      // Column(
      //   mainAxisAlignment: MainAxisAlignment.center,
      //   crossAxisAlignment: CrossAxisAlignment.start,
      //   children: <Widget>[
      //     SizedBox(height: 10),
      //     form,
      //     Expanded(
      //         child: SingleChildScrollView(
      //       child: SingleChildScrollView(
      //           scrollDirection: Axis.horizontal, child: table),
      //     )),
      //   ],
      // ),
      bottomNavigationBar: buttonBar,
    );
    return result;
  }

  _loadData() async {
    saleInquiryProduct.inquiryNo = widget.saleInquiryForm!.inquiryNo.toString();
    saleInquiryProduct.partnerId = widget.saleInquiryForm!.partnerId.toString();
    saleInquiryProduct.partnerName =
        widget.saleInquiryForm!.partnerName.toString();
    saleInquiryProduct.userId = widget.saleInquiryForm!.userId.toString();
    saleInquiryProduct.userName = widget.saleInquiryForm!.userName.toString();
    saleInquiryProduct.inquiryId = widget.saleInquiryForm!.id.toString();
    ResponseBodyApi responseBodyApi =
        await SaleInquiryProductOdooApi.page(data: {
      'type': 'browse',
      "domainList": saleInquiryProduct.toDomainList(),
    });
    if (responseBodyApi.success!) {
      tableList = responseBodyApi.data;
    }
    setState(() {});
  }
}
